package com.shuangti.gateway.filter;

import jakarta.validation.constraints.NotNull;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取header里的Session Id信息
        String token = exchange.getRequest().getHeaders().getFirst("SessionId");
        //获取请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        //如果请求是前往登录则放行
        if(path.equals("/security/login")){
            return chain.filter(exchange);
        }

        //如果token不存在或者不合法
        if(!isValidToken(token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    private boolean isValidToken(String token){
        if(token != null){
            return token.equals("yes");
        } else{
            return false;
        }
    }
}
